/*
 * Galaxium Messenger
 * Copyright (C) 2003-2007 Philippe Durand <draekz@gmail.com>
 * Copyright (C) 2007 Ben Motmans <ben.motmans@gmail.com>
 * Copyright (C) 2007 Paul Burton <paulburton89@gmail.com>
 * 
 * License: GNU General Public License (GPL)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;
using System.Drawing;
using System.IO;

using Galaxium.Core;
using Galaxium.Gui;
using Galaxium.Protocol;

using Anculus.Core;

namespace Galaxium.Protocol.Msn
{
	public class MsnEmoticon: MsnObject, IEmoticon
	{
		string[] _equivalents;
		string _filename;
		int _width = -1;
		int _height = -1;
		
		public string[] Equivalents
		{
			get { return _equivalents; }
			set { _equivalents = value; }
		}
		
		public string Filename
		{
			get { return ((!string.IsNullOrEmpty (_filename)) && File.Exists (_filename)) ? _filename : CacheFilename; }
			set
			{
				_filename = value;
				
				if (File.Exists (_filename))
					Data = File.ReadAllBytes (_filename);
				else
					Data = new byte[0];
				
				Location = Path.GetFileName (_filename);
			}
		}
		
		public string Name
		{
			get { return Friendly; }
			set { Friendly = value; }
		}

		public int Width
		{
			get
			{
				if (_width < 0)
				{
					try
					{
						Image img = Image.FromStream (new MemoryStream (Data));
						_width = img.Width;
					}
					catch
					{
						_width = 0;
					}
				}
				
				return _width;
			}
		}
		
		public int Height
		{
			get
			{
				if (_height < 0)
				{
					try
					{
						Image img = Image.FromStream (new MemoryStream (Data));
						_height = img.Height;
					}
					catch
					{
						_height = 0;
					}
				}
				
				return _height;
			}
		}
		
		public MsnEmoticon (MsnSession session, IEmoticon basis)
			: base (session)
		{
			Type = MsnObjectType.Emoticon;

			Filename = basis.Filename;
			Data = basis.Data;
			_equivalents = basis.Equivalents;
			Name = basis.Name;
		}

		public MsnEmoticon (MsnSession session, string context, params string[] equivalents)
			: base (session, context)
		{
			Type = MsnObjectType.Emoticon;
			
			_equivalents = equivalents;
		}
		
		protected override void OnDataChanged ()
		{
			_width = -1;
			_height = -1;
			
			base.OnDataChanged ();
		}
	}
}
